package com.elf.zero.widget;

import android.content.Context;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.elf.zero.app.AbsLinearLayout;
import com.elf.zero.app.R;

/**
 * 查询输入控件
 */
public class SearchInputWidget extends AbsLinearLayout {

    private EditText txt_key;
    private ImageView iv_cancel;
    private Button btn_search;

    private OnSearchListener mOnSearchListener;

    public SearchInputWidget(Context context) {
        super(context);
    }

    public SearchInputWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.zero_widget_search_input;
    }

    @Override
    protected void initView(AttributeSet attrs) {
        txt_key = findViewById(R.id.txt_key);
        iv_cancel = findViewById(R.id.iv_cancel);
        iv_cancel.setVisibility(GONE);
        iv_cancel.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                txt_key.setText("");
            }
        });
        btn_search = findViewById(R.id.btn_search);
        btn_search.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                search();
            }
        });

        txt_key.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String key = txt_key.getText().toString();
                iv_cancel.setVisibility(TextUtils.isEmpty(key) ? GONE : VISIBLE);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public void setSearchKey(String key) {
        txt_key.setText(key);
    }

    public String getSearchKey(){
        return txt_key.getText().toString();
    }

    public void search() {
        if (mOnSearchListener != null) {
            mOnSearchListener.search(txt_key.getText().toString());
        }
    }

    public void setOnSearchListener(OnSearchListener listener) {
        mOnSearchListener = listener;
    }

    public interface OnSearchListener {
        void search(String key);
    }
}
